package com.cxdr.awsips.distribute.net;

import java.io.IOException;
import java.net.ConnectException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

import com.cxdr.awsips.common.logger.LogFactory;
/**
 * FTP工具类
 * @author pugang
 *
 */

public class FTPUtils {
	private static Logger logger = LogFactory.makeNewLogger(FTPUtils.class);
	public  FtpType ftpType;
	public static enum FtpType{
		vsFTPd,Pure_FTPd
	}
	public static FTPClient loginFtp(String host,  String username,
			String password)  throws IOException{
		return loginFtp(host,0,username,password);
	}
	
	public static FTPClient loginFtp(String host, int port, String username,
			String password) throws IOException{
		FTPClient client = new FTPClient();
		if (port <=0) {
			port = client.getDefaultPort();
		}
		FtpType ftpType = FtpType.vsFTPd;
		int trier = 0;
		logger.info("Connected to " + host );
		while(!client.isConnected()){
			try{
			client.connect(host, port);
			String replyString = client.getReplyString();
			if(client.getReplyCode() == 220){
				if(replyString.contains("Pure")){
					ftpType = FtpType.Pure_FTPd;
				}
			}
			logger.info(client.getReplyString());
			if(client.isConnected()){
				logger.info("Connected to " + host +" success");
				break;
			}
			}catch(IOException ie){
				if(trier>=3){
					throw ie;
				}
				logger.error("IOException:"+ie.getMessage());
				logger.error("host:"+host+"||port:"+port+"||username:"+username+"||password:"+password);
				logger.error("system will try aign");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				trier++;
			} 
		}
		if (!client.login(username, password)) {
			logger.error("Could not login to " + host);
			logger.error("Invaild user ,please check the username and password");
			throw new ConnectException("Invaild user ,please check the username and password");
		}
		logger.info(client.getReplyString());
		logger.info("login to "+host+" success");
		if(ftpType == FtpType.Pure_FTPd){
			logger.info("Ftp server is pure-ftp");
			logger.info("Set the ftp server into ASV Model");
			client.enterLocalActiveMode();
		}else{
			logger.info("Set the ftp server into PASV Model");
			client.enterLocalPassiveMode();
		}
		logger.info("The sever control encode is:"+client.getControlEncoding());
		String systemFileEncoding = System.getProperty("file.encoding");
		logger.info("The client default encode is:"+systemFileEncoding);
		logger.info("Set the control encoding :"+systemFileEncoding);
		client.setControlEncoding("gbk");
		logger.info(client.getReplyString());
		return client;
	}

	public FtpType getFtpType() {
		return ftpType;
	}
}
